import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/controller/imageController.dart';
import 'package:qianyi/controller/webSockerController.dart';
import 'package:qianyi/entity/message/Message.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/pages/home/community/page_view/like/mock.dart';
import 'package:qianyi/pages/home/message/firends_dialog.dart';
import 'package:qianyi/pages/home/message/qr_scan.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/view_model/message/message_view_model.dart';
import 'package:qianyi/view_model/message/user_record_view_model.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:get/get.dart';
import 'package:scan/scan.dart';
import 'package:shimmer_animation/shimmer_animation.dart';

import '../../../network/http_config.dart';
import '../../../ui/widget/custom_refresh.dart';
import 'package:badges/badges.dart' as badges;

class PageViewMessage extends StatefulWidget {
  const PageViewMessage({Key? key}) : super(key: key);

  @override
  State<PageViewMessage> createState() => _PageViewMessageState();
}

class _PageViewMessageState extends State<PageViewMessage> with AutomaticKeepAliveClientMixin {
  List<MockLike> lists = [];
  ScanController controller = ScanController();
  WebSocketController webSocketController = Get.find();

  UserRecordViewModel? userRecordViewModel;
  HomeTabController homeTabController = Get.find();
  TokenController tokenController = Get.find();
  ImageAvatarController imageAvatarController = Get.find();
  bool isLoad = true;
  @override
  void initState() {
    super.initState();

    setState(() {
      lists = MockLike.get();
    });
  }

  @override
  Widget build(BuildContext context) {
    return
      Container(
      color: Colors.white,
      child: SafeArea(
        child: Column(
          children: [
            AppBar(
              automaticallyImplyLeading: false,
              title: const Text('消息'),
              actions: [
                PopupMenuButton(
                  padding: EdgeInsets.zero,
                  icon: Icon(
                    Icons.add,
                    size: WcaoTheme.fsBase * 1.75,
                  ),
                  onSelected: (item) async {
                    if (item == 1) {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (_) => const QrScan(),
                        ),
                      );
                    } else if (item == 2) {
                      showDialog(
                        context: context,
                        barrierDismissible: true,
                        builder: (BuildContext context) =>
                            const FirendsDialog(),
                      );
                    }
                  },
                  itemBuilder: (BuildContext context) => [
                    PopupMenuItem(
                      padding: const EdgeInsets.only(left: 12),
                      child: Row(
                        children: [
                          const Icon(Icons.crop_free),
                          Container(
                            margin: const EdgeInsets.only(left: 8),
                            child: const Text('扫一扫'),
                          ),
                        ],
                      ),
                      value: 1,
                    ),
                    PopupMenuItem(
                      padding: const EdgeInsets.only(left: 12),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Icon(Icons.how_to_reg),
                          Container(
                            margin: const EdgeInsets.only(left: 8),
                            child: const Text('添加好友'),
                          ),
                        ],
                      ),
                      value: 2,
                    ),
                  ],
                )
              ],
            ),
            Expanded(
              child:  MultiProvider(
                  providers: [
                    ChangeNotifierProvider(create: (context) => MessageViewModel()),
                    ChangeNotifierProvider(create: (context) => UserRecordViewModel()),


                  ],

                  child: Consumer<MessageViewModel>(
                      builder: (context, viewModel, child) {
                        webSocketController.messageViewModel = viewModel;
                        return CustomRefresh(
                            isMaterialHeader:true,
                            controller: viewModel.refreshController,
                            enablePullUp: true,
                            onRefresh: () async {
                              viewModel.onRefresh();
                              userRecordViewModel!.onRefresh();
                            },
                            onLoading: () async {
                              viewModel.onLoading();
                            },
                            child: SingleChildScrollView(
                              child: Column(
                                children: [
                                  search(),
                                  Column(
                                    children: viewModel.datas
                                        .map(
                                          (e) => InkWell(
                                        child: listCard(e),
                                        onTap: () async {
                                          Message item = e;
                                          homeTabController.messageItem = e;

                                          Map<String, dynamic> params3 = {
                                            "sendId":homeTabController.messageItem!.sendId,
                                            "acceptId":tokenController.uid
                                          };
                                          HttpManager.getInstance().request(url: '/platform/chat/updateRecordCount',method: Method.get,params: params3) ;
                                          imageAvatarController.isLoad.value = true;
                                          imageAvatarController.setAvatar(item);
                                          Get.toNamed('/message/chat');
                                        },
                                      ),
                                    )
                                        .toList(),
                                  ),
                                ],
                              ),
                            )

                        );
                      })
              )

              ,
            )

            ,
          ],
        ),
      ),
    );
  }

  Container listCard(Message item) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      margin: const EdgeInsets.only(top: 24),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(
            radius: 28,
            backgroundColor: Colors.white10,
            backgroundImage: NetworkImage(item.avatar!),
          ),
          Expanded(
            child: Container(
              padding: const EdgeInsets.only(bottom: 5),
              margin: const EdgeInsets.only(left: 24),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                    width: .5,
                    color: WcaoTheme.placeholder.withOpacity(.5),
                  ),
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        item.username!,
                        style: TextStyle(
                          fontSize: WcaoTheme.fsXl,
                          fontWeight: FontWeight.bold,
                        ),
                      ),

                    ],
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 4),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.only(right: 24),
                            child: Text(
                              item.content!,
                              style: TextStyle(
                                overflow: TextOverflow.ellipsis,
                                color: WcaoTheme.secondary,
                                fontSize: WcaoTheme.fsBase,
                              ),
                            ),
                          ),
                        ),
                        item.count! > 0?CircleAvatar(
                          radius: 10,
                          backgroundColor: WcaoTheme.primary,
                          child: Text(
                            '${item.count!}',
                            style: TextStyle(fontSize: WcaoTheme.fsSm),
                          ),
                        ):Text("")
                      ],
                    ),
                  ),
                  Row(
                    // mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text(
                        DateTime.fromMillisecondsSinceEpoch(int.parse(item.time!)).toString(),
                        style: TextStyle(
                            fontSize: WcaoTheme.fsSm,
                            color: WcaoTheme.secondary),
                      )
                    ],
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Container search() {
    return Container(
        margin: const EdgeInsets.only(top: 12),
        padding: const EdgeInsets.symmetric(horizontal: 12),
        height: 56,
        child: Consumer<UserRecordViewModel>(
            builder: (context, viewModel, child) {
                userRecordViewModel = viewModel;
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    // 第一个Column组件，包含第一个Row组件
                    GestureDetector(
                      onTap: () {
                        Map<String,String> params = {
                          "uid":tokenController.uid,
                          "type":"1"
                        };
                        HttpManager.getInstance().request(url: '/platform/user/clearUserRecord',params: params,method: Method.get).then((value) => {
                          userRecordViewModel!.onRefresh()
                        });
                        Get.toNamed("/message/likeAndCollect");
                      },
                      child: Column(
                        children: [
                          Obx(() => webSocketController.listenData['agreeCollectionCount']!=null&&webSocketController.listenData['agreeCollectionCount']>0?
                          badges.Badge(
                            //    样式
                            badgeStyle: badges.BadgeStyle(
                                badgeColor: WcaoTheme.primary,
                                shape: badges.BadgeShape.circle, // 形状
                                borderRadius: BorderRadius.circular(10)),

                            badgeContent: Text('${webSocketController.listenData['agreeCollectionCount']!}',style: TextStyle(fontSize:13,color: Colors.orange),)
                            ,
                            child: Icon(Icons.favorite, color: WcaoTheme.primary),
                          )
                              :badges.Badge(
                            //    样式
                            badgeStyle: badges.BadgeStyle(
                                badgeColor: WcaoTheme.primary,
                                shape: badges.BadgeShape.circle, // 形状
                                borderRadius: BorderRadius.circular(10),
                                padding : const EdgeInsets.all(0)
                            ),


                            child: Icon(Icons.favorite, color: WcaoTheme.primary),
                          )


                          ),
                          Text("赞和收藏",style: TextStyle(fontSize: 16),)

                        ],
                      ),
                    )
                    ,


                    // 第二个Row组件
                    GestureDetector(
                      onTap: () {
                        Map<String,String> params = {
                          "uid":tokenController.uid,
                          "type":"2"
                        };
                        HttpManager.getInstance().request(url: '/platform/user/clearUserRecord',params: params,method: Method.get).then((value) => {
                        userRecordViewModel!.onRefresh()
                        });
                        Get.toNamed("/message/followScreen");
                      },
                      child:  Column(
                        children: [
                          Row(
                            children: [
                              Obx(() => webSocketController.listenData['addFollowCount']!=null&&webSocketController.listenData['addFollowCount']>0?
                              badges.Badge(
                                //    样式
                                badgeStyle: badges.BadgeStyle(
                                    badgeColor: WcaoTheme.primary,
                                    shape: badges.BadgeShape.circle, // 形状
                                    borderRadius: BorderRadius.circular(10)),

                                badgeContent: Text('${webSocketController.listenData['addFollowCount']!}',style: TextStyle(fontSize:13,color: Colors.orange),)
                                ,
                                child: Icon(Icons.add_box_rounded, color: Colors.green),
                              )
                                  :badges.Badge(
                                //    样式
                                badgeStyle: badges.BadgeStyle(
                                    badgeColor: WcaoTheme.primary,
                                    shape: badges.BadgeShape.circle, // 形状
                                    borderRadius: BorderRadius.circular(10),
                                    padding : const EdgeInsets.all(0)
                                ),


                                child: Icon(Icons.add_box_rounded, color: Colors.green),
                              )


                              )
                            ],
                          ),

                          Text('关注', style: TextStyle(fontSize: 16)),

                        ],
                      ),

                    ),
                    // 第三个Row组件
                    GestureDetector(
                      onTap: (){
                        Map<String,String> params = {
                          "uid":tokenController.uid,
                          "type":"3"
                        };
                        HttpManager.getInstance().request(url: '/platform/user/clearUserRecord',params: params,method: Method.get).then((value) => {
                          userRecordViewModel!.onRefresh()
                        });
                       Get.toNamed("/message/commentScreen");
                      },
                      child:  Column(
                        children: [
                          Row(
                            children: [
                              Obx(() => webSocketController.listenData['noreplyCount']!=null&&webSocketController.listenData['noreplyCount']>0?
                              badges.Badge(
                                //    样式
                                badgeStyle: badges.BadgeStyle(
                                    badgeColor: WcaoTheme.primary,
                                    shape: badges.BadgeShape.circle, // 形状
                                    borderRadius: BorderRadius.circular(10)),

                                badgeContent: Text('${webSocketController.listenData['noreplyCount']!}',style: TextStyle(fontSize:13,color: Colors.orange),)
                                ,
                                child: Icon(Icons.comment, color: Colors.orange),
                              )
                                  :badges.Badge(
                                //    样式
                                badgeStyle: badges.BadgeStyle(
                                    badgeColor: WcaoTheme.primary,
                                    shape: badges.BadgeShape.circle, // 形状
                                    borderRadius: BorderRadius.circular(10),
                                    padding : const EdgeInsets.all(0)
                                ),


                                child: Icon(Icons.comment, color: Colors.orange),
                              )


                              )



                            ],
                          ),

                          Text('评论和@', style: TextStyle(fontSize: 16)),
                        ],
                      )
                      ,
                    )
                  ],
                );
            }
        )



      // Container(
      //   decoration: BoxDecoration(
      //     borderRadius: BorderRadius.circular(24),
      //     color: WcaoTheme.bgColor,
      //   ),
      //   child: TextField(
      //     enableSuggestions: false,
      //     autocorrect: false,
      //     style: TextStyle(fontSize: WcaoTheme.fsBase),
      //     decoration: const InputDecoration(
      //       hintText: "请输入搜索关键词",
      //       contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 16),
      //       enabledBorder: OutlineInputBorder(
      //         borderSide: BorderSide.none,
      //       ),
      //       focusedBorder: OutlineInputBorder(
      //         borderSide: BorderSide.none,
      //       ),
      //     ),
      //   ),
      // ),
    );
      ;

  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
